document.getElementById('exportBtn').addEventListener('click', async () => {
    const btn = document.getElementById('exportBtn');
    const statusEl = document.getElementById('status');

    // 保存原始状态
    const originalText = btn.textContent;
    btn.disabled = true;
    btn.textContent = "正在导出...";
    statusEl.textContent = "正在处理表格数据...";
    statusEl.style.color = "#666";

    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        // 发送消息并等待响应
        const response = await chrome.runtime.sendMessage({
            action: "exportTables",
            tabId: tab.id
        });

        // 判断结果
        if (response.success) {
            statusEl.textContent = `✓ 成功导出 ${response.tableCount} 个表格`;
            statusEl.style.color = "#4CAF50";
        } else {
            throw new Error(response.error || "发生未知错误");
        }
    } catch (error) {
        statusEl.textContent = `错误: ${error.message}`;
        statusEl.style.color = "#F44336";
        console.error("表格导出失败:", error);
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;

        // 3秒后清除成功状态
        if (statusEl.style.color === "#4CAF50") {
            setTimeout(() => statusEl.textContent = "", 3000);
        }
    }
});